package com.starinside.wp.service.impl;

import com.google.common.collect.ImmutableMap;
import com.starinside.wp.domain.familyTest.*;
import com.starinside.wp.foundation.DO.ObsPointRecordItemDO;
import com.starinside.wp.foundation.exception.BusinessException;
import com.starinside.wp.foundation.query.base.PagerQuery;
import com.starinside.wp.foundation.vo.BindedBabyVO;
import com.starinside.wp.repository.BabyNativeRepository;
import com.starinside.wp.repository.teststore.*;
import com.starinside.wp.service.ObsPointService;
import com.starinside.wp.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ObsPointServiceImpl implements ObsPointService {

    @Autowired
    private TestStoreObsPointRepository obsPointRepository;

    @Autowired
    private TestStoreObsPointOptionRepository optionRepository;

    @Autowired
    private TestStoreObsTaskRepository taskRepository;

    @Autowired
    private TestStoreObsPointScoreRepository scoreRepository;

    @Autowired
    BabyNativeRepository babyNativeRepository;

    @Autowired
    TestStoreRepository testStoreRepository;

    @Override
    public List<TestStoreObsPoint> getObsPointByTestStoreId(Integer testStoreId){
        return obsPointRepository.findByTestStoreIdAndIsDelete(testStoreId, false);
    }

    @Override
    public Object getObsPointTaskByChildrenIds(String[] childrenId, PagerQuery page) {

        Pageable pageable = PageRequest.of(page.getPageNum(), page.getPageSize(), Sort.Direction.DESC, "created");

        List<TestStoreObsTask>  result = taskRepository.findAllByChildrenIdInOrderByCreatedDesc(childrenId, pageable);

        long count = taskRepository.countAllByChildrenIdInOrderByCreatedDesc(childrenId);
        PageImpl<TestStoreObsTask> feeds1 = new PageImpl<>(result, pageable, count);

        ImmutableMap<String, Object> of = ImmutableMap.of("content", feeds1.getContent(), "totalElements",
                feeds1.getTotalElements(), "totalPages", feeds1.getTotalPages(), "last", pageable.getPageNumber() + 1 == feeds1.getTotalPages());

        return of;
    }

    @Override
    public TestStoreObsTask getObsPointTask(String taskId) {
        TestStoreObsTask task = taskRepository.findFirstById(taskId);
        if(task != null){
            task.setScores(getObsPointScore(taskId));
        }
        return task;
    }

    @Override
    public List<TestStoreObsPointScore> getObsPointScore(String taskId) {
        return scoreRepository.findAllByTaskId(taskId);
    }

    @Override
    public TestStoreObsTask saveObsPointTask(String parentId, String childrenId, Integer planId, List<ObsPointRecordItemDO> items){

        BindedBabyVO baby = babyNativeRepository.getBindedBaby(childrenId);

        TestStore testStore = testStoreRepository.findFirstByIdAndIsDelete(planId, 0);

        if(baby == null || testStore == null ){
            throw new BusinessException("提交了错误的评测id 或者 没有宝宝");
        }

        int month = DateUtil.betweenMonths(new Date(), baby.getBirthday()) + 1;

        String title = baby.getNickName() + "<" + testStore.getTitle() + ">的观测记录";

        //Integer testStoreId, String childrenId, Byte month, String title, String uploadFiles, Byte fileType, String image, String video
        TestStoreObsTask task = TestStoreObsTask.of(planId, childrenId, (byte) month, title, null, null, null, null );
        taskRepository.save(task);

        List<TestStoreObsPointScore> scores = new ArrayList<>();
        task.setScores(scores);

        int sum = 0;
        for(ObsPointRecordItemDO item : items){
            TestStoreObsPoint point = obsPointRepository.findByIdAndTestStoreIdAndIsDelete(item.getObsPointId(), planId, false);
            TestStoreObsPointOption option = optionRepository.findByIdAndAndObsPointAndIsDelete(item.getOptionId(), point, false);
            if(option == null || point == null){
                throw new BusinessException("提交了错误的评测选项");
            }
//            (Integer testStoreId, String taskId, Integer obsPointId, Integer obsPointType, String parentId, String childrenId, Integer obsPointOptionId, Integer score, Byte month) {
            String content = point.getTitle() + "：" + option.getTitle();
            TestStoreObsPointScore score = TestStoreObsPointScore.of(planId, task.getId(), item.getObsPointId(), point.getTestTypeId(), parentId, childrenId, item.getOptionId(), option.getScore(), (byte) month , content);

            sum += option.getScore();

            scoreRepository.save(score);
            scores.add(score);
        }

        task.setSum(sum);
        taskRepository.save(task);

        return task;
    }
}
